// pages/me/me.js
const computedBehavior = require('miniprogram-computed').behavior
const App = getApp()

Page({
  behaviors: [computedBehavior],
  /**
   * 页面的初始数据
   */
  data: {
    tel: '',
    userInfo: {},
    backData: null // 跳转回去的地址
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let url = wx.getStorageSync('backData')
    if (url) {
      this.setData({
        backData: JSON.parse(url)
      })
    }
  },
  onShow() {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      if (wx.getStorageSync('environment')) {
        this.getTabBar().setData({
          selected: 1
        })
      } else {
        this.getTabBar().setData({
          selected: 2
        })
      }
    }
    if (App.globalData.userInfo && App.globalData.userInfo.user) {
      this.getUserPhone()
    } else {
      this.getPhone()
    }
  },
  computed: {
    telPhone(data) {
      // 注意： computed 函数中不能访问 this ，只有 data 对象可供访问
      // 这个函数的返回值会被设置到 this.data.sum 字段中
      let tel = data.tel;
      if (!tel) return ""
      tel = "" + tel;
      var ary = tel.split("");
      ary.splice(3, 4, "****");
      var tel1 = ary.join("");
      return tel1
    },
  },
  getUserPhone() {
    this.setData({
      userInfo: App.globalData.userInfo,
      tel: App.globalData.userInfo.user.phonenumber ? App.globalData.userInfo.user.phonenumber : ''
    })
  },
  async getPhone() {
    // 获取个人信息
    // let data = App.globalData.userInfo
    let data = await App.$axios.request({
      url: `/user/getInfo`,
      data: {},
      method: 'GET',
      loading: true,
    })
    if (data) {
      this.setData({
        userInfo: data,
        tel: data.user.phonenumber ? data.user.phonenumber : ''
      })
      if (this.data.backData && data.user.phonenumber) {
        this.jumpBack()
      }
    } else {
      setTimeout(() => {
        this.getPhone()
      }, 1000);
    }
  },
  async getPhoneNumber(e) {
    // 获取手机号
    console.log(e.detail.code) // 动态令牌
    console.log(e.detail.errMsg) // 回调信息（成功失败都会返回）
    console.log(e.detail.errno) // 错误码（失败时返回）
    if (e && e.detail.code) {
      let data = await App.$axios.request({
        url: `/parent/user/wxPhone/${e.detail.code}`,
        method: 'POST',
        loading: true,
      })
      wx.removeStorage({
        key: 'token',
      })
      App.globalData.userInfo = null
      await this.getPhone()
    }
  },
  jumpStudentList() {

  },
  jumpBack() {
    // 获取号码后跳转回去
    let backUrl = JSON.parse(JSON.stringify(this.data.backData))
    backUrl.params = JSON.parse(backUrl.params)
    if (switchBackList.includes(backUrl.url)) {
      wx.switchTab({
        url: `/${backUrl.url}`
      })
    } else {
      let keys = Object.keys(backUrl.params)
      let params = ''
      if (keys.length) {
        params = '?'
        keys.forEach((e, i) => {
          params = `${params}${e}=${backUrl.params[e]}${keys.length-1==i?'':'&'}`
        })
      }
      wx.redirectTo({
        url: `/${backUrl.url}${params}`,
        success: () => {
          wx.removeStorage({
            key: 'backData',
          })
        }
      })
    }
  },
  jumpHistory() {
    wx.navigateTo({
      url: `/pages/myHistory/myHistory`,
    })
  },
  copyToClipboard() {
    wx.setClipboardData({
      data: this.data.userInfo.user.homeCode
    })
  },
  rebind() {
    wx.navigateTo({
      url: `/pages/bindHome/bindHome`,
    })
  },
})

const switchBackList = [
  '/pages/teacherLead/teacherLead',
  '/pages/boss/boss',
  '/pages/teacher/teacher',
  '/pages/course/course',
  '/pages/index/index'
]